﻿using System.Drawing;
using System.Drawing.Imaging;
using DimsMapper.Modules;

namespace DimsMapper
{
    public class Palette
    {
        public GDI.BITMAPINFO bmi;
        public ColorPalette palette;

        public Palette(DBFile file)
        {
            Bitmap image = new Bitmap(1, 1, PixelFormat.Format8bppIndexed);
            palette = image.Palette;
            palette.Entries[0] = Color.FromArgb(0, Color.Black);

            bmi.bmiHeader.Init();
            bmi.bmiHeader.biPlanes = 1;
            bmi.bmiHeader.biBitCount = 8;
            bmi.bmiHeader.biCompression = GDI.BitmapCompressionMode.BI_RGB;
            bmi.bmiColors = new GDI.RGBQUAD[256];

            byte[] rawPal = file.ReadBytes(768);

            bmi.bmiColors[0].rgbRed   = 0;
            bmi.bmiColors[0].rgbGreen = 0;
            bmi.bmiColors[0].rgbBlue  = 255;

            for (int c = 1, i = 3; c < 256; c++)
            {
                bmi.bmiColors[c].rgbRed   = (byte)(rawPal[i++] << 2);
                bmi.bmiColors[c].rgbGreen = (byte)(rawPal[i++] << 2);
                bmi.bmiColors[c].rgbBlue  = (byte)(rawPal[i++] << 2);

                palette.Entries[c] = GetColor(c);
            }
        }

        public Color GetColor(int index)
        {
            return Color.FromArgb(bmi.bmiColors[index].rgbRed, bmi.bmiColors[index].rgbGreen, bmi.bmiColors[index].rgbBlue);
        }
    }
}
